package com.youkeyi.ddy.cloud.common.wx.applet.message.service.impl;

import com.youkeyi.ddy.cloud.common.api.basic.pub.user.PublicUserCloudService;
import com.youkeyi.ddy.cloud.common.api.basic.pub.user.dto.PublicUserListCloudDto;
import com.youkeyi.ddy.cloud.common.api.basic.pub.user.dto.PublicUserListItemCloudDto;
import com.youkeyi.ddy.cloud.common.api.basic.pub.user.param.PublicUserQueryCloudParam;
import com.youkeyi.ddy.cloud.common.response.ResponseContent;
import com.youkeyi.ddy.cloud.common.utils.SystemDateUtils;
import com.youkeyi.ddy.cloud.common.wx.applet.message.service.WxMessageService;
import com.youkeyi.ddy.cloud.common.wx.applet.message.utils.WxTemplateMessageSendUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * WxMessageServiceImpl
 *
 * @Author liuxiawang
 * @Date 5/4/23 6:15 PM
 * @Location shenzhen.china
 */
@Service
public class WxMessageServiceImpl implements WxMessageService {

    private static final Logger logger = LoggerFactory.getLogger(WxMessageServiceImpl.class);

    public static Map<String, String> messageMap = new HashMap<>();
    static {
    }

    public static Map<String, String> subscribeMessageMap = new HashMap<>();
    static {
        subscribeMessageMap.put("1", "hrCkngCmjB5NlSIDe2n41eyCkL5IUwvoPHt_-duDVGI"); // 合同到期提醒
        subscribeMessageMap.put("2", "YwcjlGLSe56OnNrrkKcDU4p1Yu5SEOp2ZbaPQNxlKRE"); // 生日祝福提醒
        subscribeMessageMap.put("3", "dfSek_XfFWzbZbQVcyRZ-8lurWYTh9fd4EnHyGf-ERA"); // 待办事项提醒
    }
    public static Map<String, String> subscribeMessageMapName = new HashMap<>();
    static {
        subscribeMessageMapName.put("1", "合同到期提醒");
        subscribeMessageMapName.put("2", "生日祝福提醒");
        subscribeMessageMapName.put("3", "待办事项提醒");
    }

    @Autowired
    private PublicUserCloudService publicUserCloudService;

    @Override
    public ResponseContent send(List<String> userKeys, String messageType, Map<String, Object> param) {
        ResponseContent rc = new ResponseContent(Boolean.TRUE, "消息发送成功");
        if (StringUtils.isBlank(messageType) || CollectionUtils.isEmpty(userKeys)) {
            return rc;
        }

        // 通过type 拿到消息模版id
        if (!messageMap.containsKey(messageType)) {
            rc.setErrorMessage("非法的消息类型");
            return rc;
        }
        String templateId = messageMap.get(messageType);

        // 通过userKeys拿到wxOpenIds
        PublicUserQueryCloudParam userQueryCloudParam = new PublicUserQueryCloudParam();
        userQueryCloudParam.setUserPrimaryKeys(userKeys);
        PublicUserListCloudDto userDtos = publicUserCloudService.query(userQueryCloudParam);
        if (userDtos != null && CollectionUtils.isNotEmpty(userDtos.getRows())) {
            List<String> wxOpenIds = userDtos.getRows().stream().map(PublicUserListItemCloudDto::getOpenId).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(wxOpenIds)) {
                wxOpenIds.forEach(wxOpenId -> {
                    Boolean b = WxTemplateMessageSendUtils.send(templateId, wxOpenId, param);
                    if (!b) {
                        logger.error("{}:{}:消息发送失败", wxOpenId, templateId);
                    }
                });
            }
        }
        return rc;
    }

    @Override
    public ResponseContent subscribeSend(List<String> userKeys, String messageType, Map<String, Object> param) {
        ResponseContent rc = new ResponseContent(Boolean.TRUE, "消息发送成功");
        if (StringUtils.isBlank(messageType) || CollectionUtils.isEmpty(userKeys)) {
            return rc;
        }

        // 通过type 拿到消息模版id
        if (!subscribeMessageMap.containsKey(messageType)) {
            rc.setErrorMessage("非法的消息类型");
            return rc;
        }
        String templateId = subscribeMessageMap.get(messageType);

        // 通过userKeys拿到wxOpenIds
        PublicUserQueryCloudParam userQueryCloudParam = new PublicUserQueryCloudParam();
        userQueryCloudParam.setUserPrimaryKeys(userKeys);
        PublicUserListCloudDto userDtos = publicUserCloudService.query(userQueryCloudParam);
        if (userDtos != null && CollectionUtils.isNotEmpty(userDtos.getRows())) {
            List<String> wxOpenIds = userDtos.getRows().stream().map(PublicUserListItemCloudDto::getOpenId).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(wxOpenIds)) {
                wxOpenIds.forEach(wxOpenId -> {
                    Boolean b = WxTemplateMessageSendUtils.subscribeSend(templateId, wxOpenId, param);
                    if (!b) {
                        logger.error("{}:{}:消息发送失败", wxOpenId, templateId);
                    }
                });
            }
        }
        return rc;
    }

    @Override
    public ResponseContent subscribeSendForTodo(List<String> toUserKeys, String todoContent, String todoCreateUserName, String todoStatus, Long todoCreateTime) {
        Map<String, Object> sendParam = new HashMap<>();
        sendParam.put("thing1", new WxTemplateMessageSendUtils.WeChatTemplateMsg(todoContent));
        sendParam.put("thing14", new WxTemplateMessageSendUtils.WeChatTemplateMsg(todoCreateUserName));
        sendParam.put("phrase5", new WxTemplateMessageSendUtils.WeChatTemplateMsg(todoStatus));
        sendParam.put("time19", new WxTemplateMessageSendUtils.WeChatTemplateMsg(SystemDateUtils.ofPattern(todoCreateTime, "yyyy-MM-dd HH:mm:ss")));
        return subscribeSend(toUserKeys, "3", sendParam);
    }

    @Override
    public ResponseContent subscribeSendForBirthday(List<String> toUserKeys, String remindContent, String birthdayEmployeeName, Long birthday) {
        Map<String, Object> sendParam = new HashMap<>();
        sendParam.put("time1", new WxTemplateMessageSendUtils.WeChatTemplateMsg(SystemDateUtils.ofPattern(birthday, "yyyy-MM-dd")));
        sendParam.put("thing2", new WxTemplateMessageSendUtils.WeChatTemplateMsg(birthdayEmployeeName));
        sendParam.put("thing3", new WxTemplateMessageSendUtils.WeChatTemplateMsg(remindContent));
        sendParam.put("thing4", new WxTemplateMessageSendUtils.WeChatTemplateMsg(SystemDateUtils.ofPattern(birthday, "yyyy-MM-dd")));
        return subscribeSend(toUserKeys, "2", sendParam);
    }

    @Override
    public ResponseContent subscribeSendForContract(List<String> toUserKeys, String remindContent, String contractName, String contractCode, Long startTime, Long endTime) {
        Map<String, Object> sendParam = new HashMap<>();
        sendParam.put("thing4", new WxTemplateMessageSendUtils.WeChatTemplateMsg(remindContent));
        sendParam.put("thing6", new WxTemplateMessageSendUtils.WeChatTemplateMsg(contractName));
        sendParam.put("character_string5", new WxTemplateMessageSendUtils.WeChatTemplateMsg(contractCode));
        sendParam.put("thing7", new WxTemplateMessageSendUtils.WeChatTemplateMsg(SystemDateUtils.ofPattern(startTime, "yyyy-MM-dd")));
        sendParam.put("thing8", new WxTemplateMessageSendUtils.WeChatTemplateMsg(SystemDateUtils.ofPattern(endTime, "yyyy-MM-dd")));
        return subscribeSend(toUserKeys, "1", sendParam);
    }
}
